<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\Supplier;

/**
 * 供应商价目管理
 *
 * @icon fa fa-circle-o
 */
class PriceList extends Backend
{

    /**
     * PriceList模型对象
     * @var \app\admin\model\PriceList
     */
    protected $model = null;

    /**
     * 原料模型对象
     * @var \app\admin\model\ClothmakingRaw
     */
    protected $clothmakingRaw = null;

    /**
     * 包材模型对象
     * @var \app\admin\model\PackageMaterial
     */
    protected $packageMaterial = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\PriceList;
        $this->clothmakingRaw = new \app\admin\model\ClothmakingRaw;
        $this->packageMaterial = new \app\admin\model\PackageMaterial;
        $this->view->assign("materialTypeList", $this->model->getMaterialTypeList());
    }

    /**
     * 供应商价目列表页
     * 
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $this->request->filter(['strip_tags']);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = $this->appendMaterialName($list);

            return json(['total' => $total, 'rows' => $list]);
        }

        return $this->view->fetch();
    }

    /**
     * 获取物料信息
     * @return \think\Response
     */
    public function getMaterialInfo()
    {
        $params = $this->request->post();
        $response = ['total' => 0, 'rows' => []];
        if (empty($params['searchKey'])) {
            $type = $params['type'];
            $data = $this->getMaterialByType($type);
            $response['total'] = count($data);
            $response['rows'] = $data;
            return json($response);
        } else {
            // return $params;
            // 根据供应类型查询详细信息
            if ($params['type'] == 0) {
                $goodsData = $this->clothmakingRaw
                    ->where('id', $params['keyValue'])
                    ->field('id,name')
                    ->select();
            } else {
                $goodsData = $this->packageMaterial
                    ->where('id', $params['keyValue'])
                    ->field('id,name')
                    ->select();
            }

            $response['rows'] = $goodsData;
            $response['total'] = count($goodsData);

        }

        return json($response);
    }

    /**
     * 为列表数据添加物料名称和供应商名称
     * @param array $list 列表数据
     * @return array
     */
    protected function appendMaterialName($list)
    {
        foreach ($list as &$item) {
            // 获取物料名称
            if ($item['material_type'] == '原料') {
                $materialInfo = $this->clothmakingRaw->where('id', $item['material_id'])->find();
                $item['material_name'] = $materialInfo ? $materialInfo['name'] : '未知原料';
            } elseif ($item['material_type'] == '包材') {
                $materialInfo = $this->packageMaterial->where('id', $item['material_id'])->find();
                $item['material_name'] = $materialInfo ? $materialInfo['name'] : '未知包材';
            }

            // 获取供应商名称
            $supplierInfo = Db::name('supplier')->where('id', $item['supplier_id'])->find();
            $item['supplier_name'] = $supplierInfo ? $supplierInfo['name'] : '未知供应商';
        }
        unset($item);

        return $list;
    }
    /**
     * 根据类型获取材料信息
     * @param string $type 类型（0:原料, 1:包材）
     * @return array
     */
    protected function getMaterialByType($type)
    {
        return $type == '0' ?
            $this->clothmakingRaw::select() :
            $this->packageMaterial::select();
    }

    /**
     * 根据供应商id获取材料信息
     * @param string $searchValue 搜索值
     * @return array|null
     */
    public function getMaterialBySearch($searchValue)
    {
        $supplierModel = new Supplier();
        $params = $this->request->param();
        if (isset($params['keyValue'])  ){
            $type = $params['type'];
            if ($type == '0') {
                $materialInfo = $this->clothmakingRaw::where('id', $params['keyValue'])->find();
            } else {
                $materialInfo = $this->packageMaterial::where('id', $params['keyValue'])->find();
            }
            return [
                'total' => 1,
                'rows' => $materialInfo
            ];
        }
        $data = $supplierModel::find($searchValue);
        if (!$data) {
            return null;
        }
        $goods_id = explode(',', $data['goods_id']);
        $type = $data["supply_type"] == "原料" ? 0 : 1;
        $result = ["total" => 0, "rows" =>[]];
        if ($type == 0) {
            $rows =  $this->clothmakingRaw->where('id', 'in', $goods_id)->select();
        } else {
            $rows = $this->packageMaterial->where('id', 'in', $goods_id)->select();
        }
        $result = ["total" => count($rows), "rows" => $rows];
        return $result;
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}